package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.apis.wmedia.IWemdiaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemdiaClient wemdiaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1. 查询过去五天上架的所有的文章数据
       /* Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -5);*/
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> list = apArticleMapper.loadArticleListByDays(date);

        //2. 计算所有文章的得分
        if(null != list && list.size() > 0){
            List<HotArticleVo> voList = computeHotArticleVO(list);

            //3. 对数据进行排序并缓存到redis
            cacheTagToRedis(voList);
        }
    }

    /**
     * 缓存数据到redis
     * @param voList
     */
    private void cacheTagToRedis(List<HotArticleVo> voList) {
        //1. 通过feign接口查询频道数据
        ResponseResult responseResult = wemdiaClient.findAll();
        //2. 判断是否查询到了数据 如果查询到了频道数据 则缓存频道的数据
        if(null != responseResult && responseResult.getCode().equals(200) && responseResult.getData() != null){
            String json = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSONArray.parseArray(json, WmChannel.class);
            for (WmChannel wmChannel : wmChannels) { //遍历每一个频道
                List<HotArticleVo> list = voList.stream().filter(hotArticleVo ->
                        wmChannel.getId().equals(hotArticleVo.getChannelId()))
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .collect(Collectors.toList());
                //截取得分最高的30行记录
                list = list.stream().limit(30).collect(Collectors.toList());
               cacheRedis(list, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
            }
        }

        //3. 缓存推荐的数据
        voList = voList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
        cacheRedis(voList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存数据到redis
     * @param list
     * @param key
     */
    private void cacheRedis(List<HotArticleVo> list, String key) {
        cacheService.set(key, JSON.toJSONString(list));
    }

    /**
     * 计算每个文章的得分
     * @param list
     * @return
     */
    private List<HotArticleVo> computeHotArticleVO(List<ApArticle> list) {
        List<HotArticleVo> voList = new ArrayList<>(list.size());

        for (ApArticle apArticle : list) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, vo);
            Integer score = computeHotArticleScore(apArticle);
            vo.setScore(score);
            voList.add(vo);
        }

        return voList;
    }

    /**
     * 计算一个文章的得分
     * @param apArticle
     * @return
     */
    private Integer computeHotArticleScore(ApArticle apArticle) {
        Integer score = 0;
        if(null != apArticle.getViews()){
            score += apArticle.getViews();
        }
        if(null != apArticle.getLikes()){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(null != apArticle.getComment()){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(null != apArticle.getCollection()){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
